package com.yonyou.gmmc.service.pointactivity.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.HttpClientUtil;
import org.marketing.common.constants.BusinessConstant;
import org.marketing.common.constants.CommonConstant;
import org.marketing.common.dms.dto.IfMessage;
import org.marketing.common.event.EventInputDataDTO;
import org.marketing.common.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.yonyou.gmmc.common.service.BaseService;
import com.yonyou.gmmc.common.service.BaseService.MQChannelType;
import com.yonyou.gmmc.service.pointactivity.constant.PointActivityConstant;
import com.yonyou.gmmc.service.pointactivity.dao.LinkAgeMapper;
import com.yonyou.gmmc.service.pointactivity.dao.TmPotentialUserMapper;
import com.yonyou.gmmc.service.pointactivity.dao.TtOwnerLotteryMapper;
import com.yonyou.gmmc.service.pointactivity.interfaces.WechatPushInterface;
import com.yonyou.gmmc.service.pointactivity.model.TmDealer;
import com.yonyou.gmmc.service.pointactivity.model.TmKeep;
import com.yonyou.gmmc.service.pointactivity.model.TmModel;
import com.yonyou.gmmc.service.pointactivity.model.TmPotentialUser;
import com.yonyou.gmmc.service.pointactivity.model.TmRegion;

import net.sf.json.JSONObject;

@Service("LinkAgeService")
@Transactional
public class LinkAgeService {

	private Logger logger = Logger.getLogger(LinkAgeService.class);

	@Autowired
	private LinkAgeMapper linkageMapper;

	@Autowired
	private BaseService eventService;

	@Autowired
	private TmPotentialUserMapper tmPotentialUserMapper;

	@Autowired
	private TtOwnerLotteryMapper lotteryMapper;
	
	@Autowired
    private WechatPushInterface wechatPushInterface;

	private static final String parentCode = "0"; // 定义省份查询编码

	/**
	 * 根据id查询省市区
	 * 
	 * @return
	 */
	public List<TmRegion> getProvince() {
		return linkageMapper.selectProvince(parentCode);
	}

	/**
	 * 根据省份id查询下级所有城市
	 * 
	 * @param regionCode
	 * @return
	 */
	public List<TmRegion> getCity(String regionCode) {
		return linkageMapper.selectProvince(regionCode);
	}

	/**
	 * 根据城市编码查询当地经销商
	 * 
	 * @param regionCode
	 * @return
	 */
	public List<TmDealer> getDealer(String regionCode) {
		return linkageMapper.selectDealer(regionCode);
	}

	/**
	 * 根据经销商查询车辆
	 * 
	 * @param dealerCode
	 * @return
	 */
	public Map<String, Object> getModel(String dealerCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<TmModel> list = linkageMapper.selectByModel(dealerCode);
		if (list.size() == 0) {
			map.put("message", "该经销商目前没有该车辆！");
		} else {
			for (TmModel dealer : list) {
				map.put(dealer.getCarCode(), dealer.getCarName());
			}
		}
		return map;
	}

	/**
	 * 保存信息
	 * 
	 * @param tmkeep
	 */
	public void save(TmKeep tmkeep) {

		linkageMapper.save(tmkeep);

		sendToDcms(tmkeep);

		registerMember(tmkeep);
	}

	public void sendToDcms(TmKeep tmkeep) {
		String s = "";
		try {
			logger.info("将留资信息推送到DCMS——START");

			IfMessage<List<EventInputDataDTO>> message = new IfMessage<List<EventInputDataDTO>>();

			List<EventInputDataDTO> list = new ArrayList<EventInputDataDTO>();

			EventInputDataDTO dto = new EventInputDataDTO();

			dto.setDealerCode(tmkeep.getDealerCode());
			dto.setMobile(tmkeep.getPhone());
			// 这个名字对应着页面上的姓名
			dto.setName(tmkeep.getDealerName());

			list.add(dto);
			message.setIfData(list);

			String time = String.valueOf(new Date().getTime());
			String transferNo = MD5Util.MD5("ID002" + time + CommonConstant.HTTP_CLUB_KEY);

			message.setIfCode("ID002");
			message.setOccurtime(time);
			message.setTransferNo(transferNo);
			message.setDataCnt(1);
			String data = JSON.toJSONString(message).toString();

			logger.info("SendToMQ,data=" + data);

			s = eventService.sendMessage2MQ(MQChannelType.appSendCustomerData, data);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
		logger.info("将留资消息推送到DCMS——END");
	}

	/**
	 * 留资成功的自动注册成会员.
	 */
	public void registerMember(TmKeep tmkeep) {
		try {

			Map<String, Object> potentialUserMap = tmPotentialUserMapper.queryPotentialUserByOpenId(tmkeep.getOpenId());

			Long potentialUserId = null;

			if (null == potentialUserMap)
				potentialUserId = getPotentialUserInfo(tmkeep.getOpenId(), tmkeep.getDealerCode());
			else
				potentialUserId = Long.valueOf(potentialUserMap.get("POTENTIAL_USER_ID").toString());

			Map<String, Object> carOwnerMap = tmPotentialUserMapper.queryCarOwner(tmkeep.getPhone());

			Long userId = null;

			if (null == carOwnerMap)
				userId = getUserOwnerInfo(tmkeep);
			else
				userId = Long.valueOf(carOwnerMap.get("USER_ID").toString());

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userId", userId);
			map.put("openId", tmkeep.getOpenId());
			map.put("potentialUserId", potentialUserId);

			tmPotentialUserMapper.insertUserOwner(map);

			//wechatPushInterface.sendTextMsg(tmkeep.getOpenId(), "您已成功加入菱悦汇");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Long getUserOwnerInfo(TmKeep keep) {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userName", keep.getDealerName());
		map.put("phone", keep.getPhone());
		map.put("province", keep.getProvince());
		map.put("city", keep.getCity());
		map.put("userIds", "");

		// 新增一条会员数据
		tmPotentialUserMapper.insertCarOwner(map);

		logger.debug("插入会员数据返回的ID:" + map.get("userIds"));

		return Long.valueOf(map.get("userIds").toString());
	}

	public Long getPotentialUserInfo(String openId, String dealerCode) {

		logger.debug("当潜客表中不存在数据的时候,调用微信的接口,往潜客表里插入数据.");
		String token = wechatPushInterface.genToken();
		logger.debug("获取到的token是========" + token);
		JSONObject json = JSONObject.fromObject(token);
		String url = PointActivityConstant.getOpenInfoUrl.replaceAll("ACCESS_TOKEN", json.getString("token")).replaceAll("OPENID", openId);
		logger.debug("请求的url是========" + url);
		String result = HttpClientUtil.sendGetRequest(url);
		JSONObject fromObject = JSONObject.fromObject(result);
		logger.debug("请求url后返回的结果========" + result);

		TmPotentialUser user = new TmPotentialUser();
		user.setDeviceOpenId(openId);
		user.setDealerCode(dealerCode);
		user.setCreateDate(new Date());
		user.setSubscribeDate(new Date());
		user.setSex(fromObject.get("sex").toString());
		user.setCity(fromObject.get("city").toString());
		user.setCountry(fromObject.get("country").toString());
		user.setSourceType(BusinessConstant.SOURCE_TYPE_WECHAT);
		user.setProvince(fromObject.get("province").toString());
		user.setNickname(fromObject.get("nickname").toString());
		user.setHeadImgurl(fromObject.get("headimgurl").toString());
		user.setStatus(BusinessConstant.POTENTIAL_USER_STATUS_SUBSCRIBE);

		// 插入一条新关注用户信息
		int responseNum = tmPotentialUserMapper.insertSelective(user);

		if (0 != responseNum)
			return Long.valueOf(tmPotentialUserMapper.queryPotentialUserByOpenId(openId).get("POTENTIAL_USER_ID").toString());

		return null;
	}

	/**
	 * 根据省份名称查询是否存在
	 * 
	 * @param province
	 * @return
	 */
	public TmRegion checkOutProvince(String province) {
		TmRegion region = null;
		if (province != null) {
			List<TmRegion> list = linkageMapper.selectByProvince(province);
			region = list.get(0);
		}
		return region;
	}

	/**
	 * 根据城市名称查询是否存在
	 * 
	 * @param dealerCode
	 * @return
	 */
	public TmRegion checkOutCity(String city) {
		TmRegion region = null;
		if (city != null) {
			List<TmRegion> list = linkageMapper.selectByCity(city);
			region = list.get(0);
		}
		return region;
	}

	/**
	 * 根据经销商名称查询是否存在
	 */
	public TmDealer chenkOutDealer(String dealerCode) {
		TmDealer dealer = null;
		if (dealerCode != null) {
			List<TmDealer> list = linkageMapper.selectByDealer(dealerCode);
			dealer = list.get(0);
		}
		return dealer;
	}

	/**
	 * 根据车辆名称查询是否存在
	 */
	public TmModel chenkOutModel(String carCode) {
		TmModel model = null;
		if (carCode != null) {
			List<TmModel> list = linkageMapper.selectByModel(carCode);
			model = list.get(0);
		}
		return model;
	}

	/**
	 * 根据openId查询车架号
	 */
	public String findByVin(String openId) {
		String vin = null;
		if (openId != null) {
			vin = lotteryMapper.getVinByOpenId(openId);
			if (vin != null) {
				return vin;
			}
		}
		return vin;
	}

	/**
	 * 根据openId查询用户车辆所在地省份
	 * 
	 * @param openId
	 * @return
	 */
	public List<TmRegion> getCarAndProvince(String openId) {
		List<TmRegion> province = null;
		if (openId != null || !("".equals(openId))) {
			province = linkageMapper.selectByProvince(openId);
		}
		return province;
	}

	/**
	 * 根据openid查询TmKeep是否有保存信息
	 * 
	 * @return
	 */
	public TmKeep getTmKeepByOpenId(String openId) {

		return linkageMapper.getTmKeepByOpenId(openId);
	}

}
